package com.guilin.task;

import com.guilin.common.enums.ApprovalStatus;
import com.guilin.common.utils.DateUtils;
import com.guilin.domain.AlumniVisitApplication;
import com.guilin.system.service.AlumniVisitApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 校友回访申请定时任务处理
 */
@Component
@Slf4j
public class AlumniApplicationTasks {

    @Autowired
    private AlumniVisitApplicationService alumniVisitApplicationService;

    @Value("${scheduling.jobs.expired-applications.cron:0 0 1 * * ?}")
    private String expiredApplicationsCron;

    @Value("${alumni.application.task.enable-expired-processing:true}")
    private boolean enableExpiredProcessing;

    /**
     * 处理过期的回访申请
     */
    @Scheduled(cron = "${scheduling.jobs.expired-applications.cron:0 0 1 * * ?}")
    public void processExpiredApplications() {

        if (!enableExpiredProcessing) {
            log.info("过期申请处理功能已禁用");
            return;
        }

        log.info("开始处理过期的校友回访申请，时间：{}", DateUtils.getNowDate());

        // 获取当前日期
        Date now = new Date();

        // 处理已通过但过期的申请
        processExpiredApprovedApplications(now);

        // 处理待审核但过期的申请
        processExpiredPendingApplications(now);
    }

    /**
     * 处理已通过但过期的申请
     */
    private void processExpiredApprovedApplications(Date now) {
        log.info("开始处理已通过但过期的申请...");

        // 查询状态为"已通过"且结束时间早于当前时间的申请
        List<AlumniVisitApplication> applications = alumniVisitApplicationService
                .selectExpiredApplications(ApprovalStatus.APPROVED.getCode(), now);

        if (applications == null || applications.isEmpty()) {
            log.info("没有需要处理的已通过过期申请");
            return;
        }

        int successCount = 0;
        int failCount = 0;

        for (AlumniVisitApplication application : applications) {
            try {
                application.setStatus(ApprovalStatus.COMPLETED.getCode()); // 已完成
                application.setUpdateTime(now);

                // 使用更新方法
                int result = alumniVisitApplicationService.updateAlumniVisitApplication(application);

                if (result > 0) {
                    log.info("申请ID {} 已标记为已完成", application.getId());
                    successCount++;
                } else {
                    log.warn("申请ID {} 更新失败", application.getId());
                    failCount++;
                }
            } catch (Exception e) {
                log.error("处理申请ID {} 时出错: {}", application.getId(), e.getMessage());
                failCount++;
            }
        }

        log.info("已通过过期申请处理完成: 成功 {} 条, 失败 {} 条, 总计 {} 条",
                successCount, failCount, applications.size());
    }

    /**
     * 处理待审核但过期的申请
     */
    private void processExpiredPendingApplications(Date now) {
        log.info("开始处理待审核但过期的申请...");

        // 查询状态为"待审核"且结束时间早于当前时间的申请
        List<AlumniVisitApplication> applications = alumniVisitApplicationService
                .selectExpiredApplications(ApprovalStatus.PENDING.getCode(), now);

        if (applications == null || applications.isEmpty()) {
            log.info("没有需要处理的待审核过期申请");
            return;
        }

        int successCount = 0;
        int failCount = 0;

        for (AlumniVisitApplication application : applications) {
            try {
                application.setStatus(ApprovalStatus.REJECTED.getCode()); // 已拒绝
                application.setReviewOpinion("系统自动拒绝：回访时间已过");
                application.setUpdateTime(now);

                // 使用更新方法
                int result = alumniVisitApplicationService.updateAlumniVisitApplication(application);

                if (result > 0) {
                    log.info("申请ID {} 已标记为已拒绝", application.getId());
                    successCount++;
                } else {
                    log.info("申请ID {} 更新失败", application.getId());
                    failCount++;
                }
            } catch (Exception e) {
                log.info("处理申请ID {} 时出错: {}", application.getId(), e.getMessage());
                failCount++;
            }
        }

        log.info("待审核过期申请处理完成: 成功 {} 条, 失败 {} 条, 总计 {} 条",
                successCount, failCount, applications.size());
    }
}